<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/23
 * Time: 10:44
 */

namespace Home\Logic;

use Admin\Logic\MoneyLogLogic;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Core\Config;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use Common\Utils\Constants;
use Common\Utils\SmsUtils;
use Common\Utils\TemplateUtils;
use Home\Model\Page;
use Think\Exception;
use Think\Log;

class RoomLogic
{
    /**
     * 摆擂
     * @param $model 比赛模式
     * @param $money
     * @param $declaration
     * @param $password
     * @param $user 创建者
     * @param $money_type=0 int 类型
     * @param $user_id int 接收方id
     * @return array status 1 成功 0失败 2积分不足 room_id
     */
    public function addRoom($model, $money, $declaration, $password, $user, $money_type =0,$user_id=0){
        $dbModel = M();
        $dbModel->startTrans();
        try {
            if($money_type == Constants::MONEY_TYPE_GOLD){
                if($user['gold'] < $money){
                    return array('status'=>2);
                }
            }else{
                if($user['integral'] < $money){
                    return array('status'=>2);
                }
            }
            $data['model'] = $model;
            $data['integral'] = $money;
            $data['declaration'] = $declaration;
            if(!empty($password)) {
                $password = md5($password . C('MD5_KEY'));
                $data['password'] = $password;
            }
            $data['user_id'] = $user['id'];
            $data['systems_name'] = $user['systems_name'];
            $data['region'] = $user['region'];
            $data['level'] = $user['level'];
            if ($money > 100) {
                $data['integral_interval'] = 1;
            } else {
                $data['integral_interval'] = 0;
            }
            $data['status'] = Constants::ROOM_STATUS_WAIT;
            $data['create_time'] = time();
            $data['money_type'] = $money_type;
            $room_id = $dbModel->table('t_room')->add($data);
            $moneyLogic = new MoneyLogLogic();
            if($money_type == Constants::MONEY_TYPE_GOLD){
                //金币
                $dbModel->table('t_user')->where(array('id' => $user['id']))->setDec('gold', $money);
                $currentMoney = $user['gold'] - $money;
                $remark = '使用金币摆擂';
            }else{//钻石
                $dbModel->table('t_user')->where(array('id' => $user['id']))->setDec('integral', $money);
                $currentMoney = $user['integral'] - $money;
                $remark = '使用钻石摆擂';
            }
            $moneyLogic->saveMoneyLog($money,
                $currentMoney,
                Constants::MONEY_SOURCE_CREATE_ROOM,
                Constants::PUT_TYPE_OUT,
                $remark, $user['id'],$money_type, $dbModel);
            Log::write('user_id----:'.$user_id);
            if(!empty($user_id)){//发送挑战消息
                $messageLogic = new MessageLogic();
                $messageLogic->sendMessage($user['id'],$user_id,$room_id,$dbModel);
                $templateUtils = new TemplateUtils();
                $openid = D('User')->where(array('id'=>$user_id))->getField('openid');//被邀请者id
                $templateUtils->sendInviteMessage($openid,$user['nickname'],$room_id);
            }
            $dbModel->commit();
            return array('status'=>1,'room_id'=>$room_id);
        }catch (Exception $e){
            Log::write('addRoom---:'.$e->getMessage());
            $dbModel->rollback();
            return array('status'=>0);
        }
    }

    public function getRoomList($map,$pagenum=1,$pagesize=20,$user_id,$sort='',$type,$level){
        $where['_string'] = '';
        if(empty($type)){
            switch ($level){
                case Constants::LEVEL_1:
                case Constants::LEVEL_2:
                    $type = 4;
                    break;
                case Constants::LEVEL_3:
                case Constants::LEVEL_4:
                    $type = 3;
                    break;
                case Constants::LEVEL_5:
                case Constants::LEVEL_6:
                    $type = 2;
                    break;
                case Constants::LEVEL_7:
                    $type = 1;
                    break;
            }
        }
//        if(!empty($type)){
            if($type == 1){
                $map['t_room.level'] = Constants::LEVEL_7;//王者
            }else if($type == 2){
                $where['_string'] = "(t_room.level=".Constants::LEVEL_5." OR t_room.level=".Constants::LEVEL_6.')';//星耀 钻石
            }else if($type == 3){
                $where['_string'] = "(t_room.level=".Constants::LEVEL_3." OR t_room.level=".Constants::LEVEL_4.')';//铂金 黄金
//                $map['_complex'] = $where;
            }else{
                $where['_string'] = "(t_room.level=".Constants::LEVEL_1." OR t_room.level=".Constants::LEVEL_2.')';//白银 青铜
//                $map['_complex'] = $where;
            }
//        }else{
//            $map['t_room.level'] = $level;
//        }
        if(!empty($where['_string'])){
            $where['_string'] .=' AND ';
        }
        $where['_string'] .= '(t_room.status = '.Constants::ROOM_STATUS_PROCESSING.' OR'.' t_room.status = '.Constants::ROOM_STATUS_WAIT.')';
        $map['_complex'] = $where;
        $data = $this->makeQueryList($map,$pagenum,$pagesize,$user_id,$sort);
        return $data;
    }

    private function makeQueryList($map,$pagenum,$pagesize,$user_id,$sort=''){
        $startno = ($pagenum - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        if(empty($sort)){
            $sort = 't_room.id desc';
        }
        $roomList = D('Room')->join('LEFT JOIN t_user u ON u.id=t_room.user_id')
            ->join('LEFT JOIN t_user ou ON ou.id=t_room.opponent_id')
            ->field('ou.nickname as opponent_nickname,ou.head_url as o_head_url,ou.sex as opponent_sex,ou.wechat_number as o_wechat_number,ou.qq_number o_qq_number,ou.game_name as o_game_name,ou.systems_name as o_systems_name,ou.region as o_region,ou.region_name as o_region_name,u.sex as user_sex,u.nickname as user_nickname,u.head_url as head_url,u.region_name as region_name,u.qq_number qq_number,t_room.*')
            ->where($map)
            ->order($sort)->limit($limit)
            ->select();
        foreach ($roomList as $key => $value){
            $roomList[$key]['create_time'] = date('m月d日 H:i',$value['create_time']);
            $roomList[$key]['model_name'] = $value['model'] == 0 ?'1v1' : ($value['model'] == 1?'3v3':'5v5');
            $roomList[$key]['model_show_name'] = $this->switchModel($value['model']);
            if($user_id == $value['user_id'] || $user_id == $value['opponent_id']){
                $roomList[$key]['is_need_password'] = false;
            }else{
                $roomList[$key]['is_need_password'] = true;
            }
            $o_region = explode('-',$value['o_region_name']);
            $region = explode('-',$value['region_name']);
            $roomList[$key]['o_region_name'] = $o_region[1] == '' ? $o_region[0] : $o_region[1];
            $roomList[$key]['region_name'] = $region[1] == '' ? $region[0] : $region[1];
        }
        $data['list'] = $roomList;
        $count = D('Room')->where($map)->count();
        $page = new Page($pagenum, $count, $pagesize);
        $page = (array)$page;//转换为数组
        $data['page'] = $page;
        return $data;
    }

    /**
     * 获取我参与过的擂台列表
     * @param $map
     * @param int $pagenum
     * @param int $pagesize
     * @param $user_id int 当前用户id
     * @return mixed
     */
    public function getMyRoomList($map,$pagenum=1,$pagesize=20,$user_id){
        $where['_string'] = '(t_room.status = '.Constants::ROOM_STATUS_PROCESSING.' OR '.' t_room.status = '.Constants::ROOM_STATUS_WAIT.') AND (t_room.user_id = '.$user_id.' OR '.' t_room.opponent_id = '.$user_id.')';
        $map['_complex'] = $where;
        $data = $this->makeQueryList($map,$pagenum,$pagesize,$user_id);
        return $data;
    }

    public function getRoomById($room_id){
        $map['t_room.id'] = $room_id;
        $room = D('Room')->join('LEFT JOIN t_user u ON u.id=t_room.user_id')
            ->join('LEFT JOIN t_user ou ON ou.id=t_room.opponent_id')
            ->field('ou.nickname as opponent_nickname,ou.head_url as o_head_url,ou.sex as opponent_sex,ou.wechat_number as o_wechat_number,ou.qq_number o_qq_number,ou.game_name as o_game_name,ou.systems_name as o_systems_name,ou.region as o_region,ou.region_name as o_region_name,u.sex as user_sex,u.nickname as user_nickname,u.head_url as head_url,u.region_name as region_name,u.qq_number qq_number,t_room.*')
            ->where($map)
            ->find();
        $o_region = explode('-',$room['o_region_name']);
        $region = explode('-',$room['region_name']);
        $room['o_region_name'] = $o_region[1] == '' ? $o_region[0] : $o_region[1];
        $room['region_name'] = $region[1] == '' ? $region[0] : $region[1];
        $room['model_name'] = $room['model'] == 0 ?'1v1' : ($room['model'] == 1?'3v3':'5v5');
        $room['model_show_name'] = $this->switchModel($room['model']);
        return $room;
    }

    private function switchModel($model){
        switch ($model){
            case 0:
                return '1V1 墨家';
            case 1:
                return '3V3 长平';
            case 2:
                return '5V5 深渊';
            case 3:
                return '5V5 王者';
            case 4:
                return '5V5 征召';
            case 5:
                return '输赢排位赛';
            case 6:
                return '排位输赢「大」 ';
            case 7:
                return '排位输赢「小」 ';
            case 8:
                return '排位输赢「单」 ';
            case 9:
                return '排位输赢「双」 ';
            default:
                return '5V5 竞猜';
        }
    }

    //检查密码
    public function checkPassword($room_id,$password){
        $room = D('Room')->where(array('id'=>$room_id))->find();
        if(!$room){
            return false;
        }
        if($password == '' && empty($room['password'])){
            return true;
        }
        $password = md5($password . C('MD5_KEY'));
        return $room['password'] == $password;
    }

    /**
     * 打擂
     * @param $user_id int 打擂者
     * @param $room_id int 房间id
     * @return array status 0失败 1成功 2金币不足 3钻石不足 4该房间已经有挑战者 5该擂台不存在 6挑战者不能是擂主 7不能打擂 成功返回roomUser
     */
    public function challenge($user_id,$room_id){
        $model = M();
        $model->startTrans();
        $room = $model->table('t_room')->where(array('id'=>$room_id))->find();
        if(!$room){
            return array('status'=>5);
        }
        if($room['status'] != Constants::ROOM_STATUS_WAIT){
            return array('status'=>7);
        }
        if($room['user_id'] == $user_id){
            return array('status'=>6);
        }
        $opponent = $model->table('t_user')->where(array('id'=>$user_id))->find();
        if($room['money_type'] == Constants::MONEY_TYPE_GOLD){
            if($opponent['gold'] <$room['integral']){
                return array('status'=>2);
            }
        }else{
            if($opponent['integral'] <$room['integral']){
                return array('status'=>3);
            }
        }
        if(!empty($room['opponent_id'])){
            return array('status'=>4);
        }
        try{
            if($room['money_type'] == Constants::MONEY_TYPE_GOLD){
                //金币
                $model->table('t_user')->where(array('id' => $user_id))->setDec('gold', $room['integral']);
                $currentMoney = $opponent['gold'] - $room['integral'];
                $remark = '使用金币打擂(擂台号:'.$room_id.')';
            }else{//钻石
                $model->table('t_user')->where(array('id' => $user_id))->setDec('integral', $room['integral']);
                $currentMoney = $opponent['integral'] - $room['integral'];
                $remark = '使用钻石打擂(擂台号:'.$room_id.')';
            }
            $moneyLogic = new MoneyLogLogic();
            $moneyLogic->saveMoneyLog($room['integral'],
                $currentMoney,
                Constants::MONEY_SOURCE_CHALLENGE,
                Constants::PUT_TYPE_OUT,
                $remark, $user_id,$room['money_type'], $model);
            $model->table('t_room')->where(array('id'=>$room_id))->setField('opponent_id',$user_id);
            $model->table('t_room')->where(array('id'=>$room_id))->setField('playing_time',time());//更新最后更新时间
            $model->table('t_room')->where(array('id'=>$room_id))->setField('status',Constants::ROOM_STATUS_PROCESSING);
            $matchLogic = new MatchLogLogic();
            $matchLogic->saveMatchLog($room['user_id'],$user_id,$room,$model);
            $model->commit();
            $roomUser = D('User')->where(array('id'=>$room['user_id']))
                ->field('wechat_number,qq_number,systems_name,game_name,region,phone,openid')
                ->find();//获取房主信息
            //给房主发送匹配消息
            $this->sendMatchMessage($room,$roomUser);
            return array('status'=>1,'roomUser'=>$roomUser);
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
            return array('status'=>0);
        }
    }

    //给房主发送匹配消息
    private function sendMatchMessage($room,$roomUser){
        if($room['money_type'] == Constants::MONEY_TYPE_INTEGRAL && !empty($roomUser['phone'])){
            //发送短信通知
            $this->sendSmsMessage($roomUser,$room['id']);
        }
        //发送微信模板消息
        $utils = new TemplateUtils();
        $utils->sendMatchMessage($roomUser['openid'],$room['id']);
    }

    private function sendSmsMessage($roomUser,$room_id){
        $utils = new SmsUtils();
        $jsonStr = "{\"nickname\":\"".$roomUser['nickname']."\",\"room_id\":\"".$room_id."\"}";
        $utils->sendSms($roomUser['phone'],$jsonStr,Constants::SMS_TEMPLATE_MATCH);
    }

    /**
     * @param $room_id int 房间id
     * @param $password string 原密码
     * @param $new_password string 新密码
     * @param $user_id int 用户id
     * @return int status 0 失败 1成功 2擂台不存在 3不是擂主 4原始密码错误
     */
    public function modifyPassword($room_id,$password,$new_password,$user_id){
        $model = M();
        $model->startTrans();
        try {
            $room = $model->table('t_room')->where(array('id' => $room_id))->find();
            if (!$room) {
                return 2;
            }
            if ($room['status'] != Constants::ROOM_STATUS_WAIT) {
                return 4;
            }
            if ($room['user_id'] != $user_id) {
                return 3;
            }
            if($password !='') {
                $password = md5($password . C('MD5_KEY'));
            }
            $new_password = md5($new_password . C('MD5_KEY'));
            if ($room['password'] != $password) {
                return 4;
            }

            $model->table('t_room')->where(array('id' => $room_id))->setField('password', $new_password);
            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
            return 0;
        }
    }

    /**
     * 用户解散房间
     * @param $user_id int 用户id
     * @param $room_id int 房间id
     * @param $user_remark string 用户备注
     * @return int 0失败 1成功 2该用户不是擂主 3已经提交过解散申请 4当前房间不能解散
     */
    public function disbanded($user_id,$room_id,$user_remark){
        $room = D('Room')->where(array('id'=>$room_id))->find();
        if($room['user_id'] != $user_id){
            return 2;
        }
        if($room['status'] != Constants::ROOM_STATUS_WAIT){
            return 4;
        }
        $count = D('DissolveLog')->where(array('room_id'=>$room_id))->count();
        if($count > 0){
            return 3;
        }
        $model = M();
        $model->startTrans();
        try {
            $log['create_time'] = time();
            $log['user_remark'] = $user_remark;
            $log['user_id'] = $user_id;
            $log['room_id'] = $room_id;
            $log['verify'] = 1;
            $model->table('t_dissolve_log')->add($log);
            $model->table('t_room')->where(array('id'=>$room['id']))->setField('status',Constants::ROOM_STATUS_DISBANDED);
            $model->table('t_match_log')->where(array('room_id'=>$room['id']))->setField('status',Constants::MATCH_CANCEL);
//            $nickname = D('User')->where(array('id'=>$user_id))->getField('nickname');
//            $this->sendAdminMessage($room_id,$nickname);
            $this->returnMoney($room,$model);
            $model->commit();
            return 1;
        }catch (Exception $e){
            $model->rollback();
            Log::write($e->getMessage());
            return 0;
        }
    }

    //通过指定房间 返回金币或钻石
    private function returnMoney($room,$model){
        $money = $room['integral'];
        $this->returnMoneyToUser($room['money_type'],$room['user_id'],$money,$model);
    }
    /**
     * 返回钻石或金币给用户
     * @param $money_type
     * @param $user_id
     * @param $money
     * @param $model
     */
    private function returnMoneyToUser($money_type,$user_id,$money,$model){
        if($money_type == Constants::MONEY_TYPE_GOLD){
            $model->table('t_user')->where(array('id' => $user_id))->setInc('gold', $money);
            $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('gold');
            $type = '金币';
        }else{
            $model->table('t_user')->where(array('id' => $user_id))->setInc('integral', $money);
            $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('integral');
            $type = '钻石';
        }
        $remark = '解散房间返回'.$type;
        $moneyLogic = new MoneyLogLogic();
        $moneyLogic->saveMoneyLog($money,
            $currentMoney,
            Constants::MONEY_SOURCE_DISSOLVE,
            Constants::PUT_TYPE_IN,
            $remark,$user_id,$money_type,$model);
    }

    //给管理员发送消息
    private function sendAdminMessage($room_id,$nickname){
        $utils = new TemplateUtils();
        $list = D('Admin')->join('LEFT JOIN t_user u ON u.id=t_admin.user_id')
            ->where(array('t_admin.user_id'=>array('EXP','IS NOT NULL')))
            ->field('u.openid,u.nickname')
            ->select();
        foreach ($list as $key=>$value){
            $utils->sendDisbandedWaitMessage($value['openid'],$nickname,$room_id);
        }
    }

}